const koa = require("koa");
const router = require("koa-router")();

const MembersModel = require("./models/members");
const cors = require("koa2-cors");
const bodyParser = require("koa-bodyparser");
const app = new koa();
router.get("/members",async ctx=>{
    console.log(ctx.query);
    var {start,count} = ctx.query;
    if(start == undefined){
        start =0
    }
    if(count == undefined){
        count =5
    }
    var data = await MembersModel.find({}).skip(Number(start)).limit(Number(count))
    ctx.body = {
        data,
        code:200
    }
})
router.post("/doAdd",async ctx=>{
    console.log(ctx.request.body)

    var {name,age,like,playStates} = ctx.request.body;
    var db = new MembersModel({name,age,like,playStates})
    db.save(err=>{
        if(err) throw err;
    })
    ctx.redirect("/Members")
})
router.post("/doDelete",async ctx=>{
    var {id} = ctx.request.body;
    await MembersModel.remove({_id:id})
    ctx.redirect("/Members")
})
router.post("/dolike",async ctx=>{
    console.log(ctx.request.body)
    var {id,playStates} = ctx.request.body;
    await MembersModel.updateOne({_id:id},{$set:{playStates}})
    ctx.redirect("/Members")
})
app.use(cors());
app.use(bodyParser());
app.use(router.routes());
app.listen(8081)